﻿namespace Demo.Core.CommonExtension;

public static class ListExtensions
{
    /// <summary>
    /// 集合去重
    /// </summary>
    /// <param name="lst">目标集合</param>
    /// <param name="keySelector">去重关键字</param>
    /// <typeparam name="T">集合元素类型</typeparam>
    /// <typeparam name="TKey">去重关键字数据类型</typeparam>
    /// <returns>去重结果</returns>
    public static List<T> Distinct<T,TKey>(this List<T> lst,Func<T, TKey> keySelector)
    {
        List<T> result = new List<T>();
        HashSet<TKey> set = new HashSet<TKey>();
        foreach (var item in lst)
        {
            var key = keySelector(item);
            if (!set.Contains(key))
            {
                set.Add(key);
                result.Add(item);
            }
        }
        return result;
    }
}